package com.yc.damaimaven.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yc.damaimaven.entity.Cart;
import com.yc.damaimaven.entity.Result;
import com.yc.damaimaven.entity.User;
import com.yc.damaimaven.mapper.CartMapper;
import com.yc.damaimaven.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xw
 * @since 2024-07-09
 */
@RestController
@RequestMapping("/cart")
public class CartController {


    @Autowired
    ICartService cartService;
    @RequestMapping("add")
    public Result add(@SessionAttribute User myinfo, @RequestBody Cart cart){
        cart.setUid(myinfo.getUid());
        LambdaQueryWrapper<Cart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Cart::getUid, myinfo.getUid());
        lqw.eq(Cart::getPid, cart.getPid());
        Cart dbcart=cartService.getOne(lqw);
        if(dbcart==null){
            cartService.save(cart);
        } else{
            dbcart.setCount(dbcart.getCount()+cart.getCount());
            cartService.updateById(dbcart);
        }
//        LambdaQueryWrapper<Cart>lqw = new LambdaQueryWrapper<>();
//        lqw.eq(Cart::getUid,myinfo.getUid());
//        lqw.eq(Cart::getPid,cart.getPid());
//        Cart dbcart = cartService.getOne(lqw);
//        if(dbcart == null){
//            //如果数据库中没有该用户收藏加入该购物车的商品，就新增
//            cartService.save(cart);
//        } else {
//            //如果数据库中有该用户收藏加入该购物车的商品，就增加，更新记录
//            dbcart.setCount(dbcart.getCount() + cart.getCount());
//            cartService.updateById(dbcart);
//        }

        return Result.ok("添加购物车成功!");
    }

    @Autowired
    CartMapper cartMapper;
    @RequestMapping("mycart")
    public Result mycart(@SessionAttribute User myinfo){
        return cartMapper.selectMyCart(myinfo.getUid());
    }
}
